package com.binest.kolInclusion.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.WildcardQuery;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.binest.common.constant.HttpStatus;
import com.binest.common.core.domain.entity.SysUser;
import com.binest.common.core.domain.model.LoginUser;
import com.binest.common.core.page.TableDataInfo;
import com.binest.common.utils.DateUtils;
import com.binest.common.utils.uuid.IdUtils;
import com.binest.draftBox.domain.DraftBox;
import com.binest.draftBox.mapper.DraftBoxMapper;
import com.binest.hackathonInclusion.domain.HackathonInclusion;
import com.binest.inclusionExamine.domain.InclusionExamine;
import com.binest.inclusionExamine.mapper.InclusionExamineMapper;
import com.binest.inclusionExamine.service.IInclusionExamineService;
import com.binest.kolInclusionMain.domain.KolInclusionMain;
import com.binest.kolInclusionMain.mapper.KolInclusionMainMapper;
import com.binest.meetingInclusion.domain.MeetingInclusion;
import com.binest.meetingInclusionMain.domain.MeetingInclusionMain;
import com.binest.socialMediaConnection.domain.SocialMediaConnection;
import com.binest.socialMediaConnection.mapper.SocialMediaConnectionMapper;
import com.binest.socialMediaConnection.service.ISocialMediaConnectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.binest.kolInclusion.mapper.KolInclusionMapper;
import com.binest.kolInclusion.domain.KolInclusion;
import com.binest.kolInclusion.service.IKolInclusionService;

import static com.binest.common.utils.SecurityUtils.getLoginUser;

/**
 * KOL收录Service业务层处理
 *
 * @author binest
 * @date 2024-01-16
 */
@Service
public class KolInclusionServiceImpl implements IKolInclusionService {
    @Autowired
    private KolInclusionMapper kolInclusionMapper;
    @Autowired
    private IInclusionExamineService inclusionExamineService;
    @Autowired
    private KolInclusionMainMapper kolInclusionMainMapper;
    @Autowired
    private DraftBoxMapper draftBoxMapper;

    @Autowired
    private InclusionExamineMapper inclusionExamineMapper;

    @Autowired
    private SocialMediaConnectionMapper socialMediaConnectionMapper;

    @Autowired
    private ElasticsearchClient client;
    @Autowired
    private ISocialMediaConnectionService socialMediaConnectionService;
    /**
     * 查询KOL收录
     *
     * @param id KOL收录主键
     * @return KOL收录
     */
    @Override
    public KolInclusion selectKolInclusionById(String id) {
        KolInclusion res =kolInclusionMapper.selectKolInclusionById(id);
        List<SocialMediaConnection> smcList=socialMediaConnectionService.selectSocialMediaConnectionByInId(id);
        if(smcList!=null)
        {
            res.setSmcList(smcList);
        }

        return  res ;
    }

    @Override
    public KolInclusion selectEsKolInclusionById(String id) throws Exception {
        KolInclusion res = new KolInclusion();
        try {
            // 执行查询
            SearchResponse<KolInclusion> searchResponse = client.search(srBuilder -> srBuilder
                            .index("kol_inclusion")
                            // 多个id查询
                            .query(queryBuilder -> queryBuilder
                                    .ids(idsQueryBuilder -> idsQueryBuilder
                                            .values(id))
                            )
                    , KolInclusion.class);

            //解析查询结果

            List<Hit<KolInclusion>> hitList = searchResponse.hits().hits();

            res = hitList.get(0).source();

        } catch (IOException e) {
            throw new Exception("查询ES数据失败");

        }


        return res;
    }

    /**
     * 查询KOL收录列表
     *
     * @param kolInclusion KOL收录
     * @return KOL收录
     */
    @Override
    public List<KolInclusion> selectKolInclusionList(KolInclusion kolInclusion) {
        List<KolInclusion> resList=kolInclusionMapper.selectKolInclusionList(kolInclusion);
        for(KolInclusion p:resList){
            String   exStatus= inclusionExamineService.getExamineStatus(p.getId());
            if(exStatus!=null){
                p.setExStatus(exStatus);
            }else{
                p.setExStatus("");
            }
        }
        return resList;

    }

    public TableDataInfo selectKolInclusionEsList(KolInclusion kolInclusion) throws Exception {

        TableDataInfo rspData = new TableDataInfo();
        // 将多个查询条件放入list中.
        List<Query> queries = new ArrayList<>();
        List<Query> querie = new ArrayList<>();

        //最新 最热
        String type = "";
        if (kolInclusion.getType().equals("0")) {
            //最新
            type = "createTime.keyword";
        } else {
            type = "likeCount.keyword";
        }
        // 升序降序
        String esSort = "";

        if (kolInclusion.getSort().equals("0")) {
            //最新
            esSort = "Desc";
        } else {
            esSort = "Asc";
        }

        //判断中英文  0英文  1中文
        Query byLang = MatchQuery.of(a -> a
                .field("lang")
                .query(kolInclusion.getLang())
        )._toQuery();

        querie.add(byLang);

        //查询条件  关键词模糊查询
        if (kolInclusion.getNickname() != null) {

            Query byName = WildcardQuery.of(m -> m
                    .field("nickName")
                    .value("*" + kolInclusion.getNickname() + "*")

            )._toQuery();

            Query byContent = WildcardQuery.of(m -> m
                    .field("content")
                    .value("*" + kolInclusion.getNickname() + "*")

            )._toQuery();


            queries.add(byName);
            queries.add(byContent);

        }
        try {
            // 从es中根据条件查询结果.
            String finalType = type;
            String finalEsSort = esSort;
            SearchResponse<KolInclusion> searchResponse = client.search(s -> s
                            .index("kol_inclusion")
                            .query(q -> q
                                    .bool(t -> t
                                            .should(queries)
                                            .must(querie)

                                    ))
                            .from((kolInclusion.getPageNum() - 1) * kolInclusion.getPageSize())
                            .size(kolInclusion.getPageSize())
                            .sort(sort -> sort.field(f -> f.field(finalType).order(SortOrder.valueOf(finalEsSort))))
                    , KolInclusion.class);
            List<Hit<KolInclusion>> hitList = searchResponse.hits().hits();

            List<KolInclusion> list = new ArrayList<>();
            for (Hit<KolInclusion> mapHit : hitList) {
                list.add(mapHit.source());
            }

            long total = searchResponse.hits().total() != null ? searchResponse.hits().total().value() : 0;

            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(list);
            rspData.setTotal(total);

            return rspData;
        } catch (Exception e) {
            throw new Exception("【查询 -> 失败】从es中组合查询出错，错误信息为：{}");
        }


    }

    /**
     * 新增KOL收录
     *
     * @param kolInclusion KOL收录
     * @return 结果
     */
    @Override
    public String insertKolInclusion(KolInclusion kolInclusion) {
        kolInclusion.setCreateTime(DateUtils.getNowDate());
        //判断存草稿箱还是提交收录
        //存草稿箱
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getUser();

        //判断是否有主表id
        if (kolInclusion.getMainId() == null) {


            String uuid = IdUtils.simpleUUID();
            String mainId = IdUtils.simpleUUID();
            kolInclusion.setId(uuid);
            kolInclusion.setMainId(mainId);
            kolInclusion.setCreateTime(DateUtils.getNowDate());
            kolInclusion.setCreateBy(currentUser.getUserId().toString());

            //新增社交媒体链接
            if (kolInclusion.getSmcList() != null) {

                for (SocialMediaConnection s : kolInclusion.getSmcList()) {

                    s.setId(IdUtils.simpleUUID());
                    //收录id
                    s.setInclusionId(uuid);
                    s.setCreateBy(currentUser.getUserId().toString());
                    s.setCreateTime(DateUtils.getNowDate());
                    socialMediaConnectionMapper.insertSocialMediaConnection(s);
                }

            }
            //新增kol收录
            kolInclusionMapper.insertKolInclusion(kolInclusion);
            //新增kol收录主表
            KolInclusionMain kolInclusionMain = new KolInclusionMain();
            kolInclusionMain.setId(mainId);
            kolInclusionMain.setCreateTime(DateUtils.getNowDate());
            kolInclusionMain.setCreateBy(currentUser.getUserId().toString());
            kolInclusionMainMapper.insertKolInclusionMain(kolInclusionMain);


            if (kolInclusion.getSubmitType().equals("0")) {

                DraftBox draftBox = new DraftBox();
                draftBox.setId(IdUtils.simpleUUID());
                //kol昵称
                draftBox.setName(kolInclusion.getNickname());
                //类型  kol
                draftBox.setType("4");
                draftBox.setProjectId(uuid);
                draftBox.setUserId(currentUser.getUserId().toString());
                draftBox.setCreateBy(currentUser.getUserId().toString());
                draftBox.setCreateTime(DateUtils.getNowDate());
                draftBoxMapper.insertDraftBox(draftBox);
            } else {

                InclusionExamine inclusionExamine = new InclusionExamine();

                inclusionExamine.setId(IdUtils.simpleUUID());
                //未审核
                inclusionExamine.setStatus("0");
                inclusionExamine.setName(kolInclusion.getNickname());
                //类型 kol
                inclusionExamine.setType("4");
                inclusionExamine.setProjectId(uuid);
                inclusionExamine.setUserId(currentUser.getUserId().toString());
                inclusionExamine.setCreateBy(currentUser.getUserId().toString());
                inclusionExamine.setCreateTime(DateUtils.getNowDate());
                inclusionExamineMapper.insertInclusionExamine(inclusionExamine);


            }

        } else {
            String uuid = IdUtils.simpleUUID();
            kolInclusion.setId(uuid);
            kolInclusion.setCreateTime(DateUtils.getNowDate());
            kolInclusion.setCreateBy(currentUser.getUserId().toString());

            //新增kol收录
            kolInclusionMapper.insertKolInclusion(kolInclusion);
            //新增社交媒体链接
            if (kolInclusion.getSmcList() != null) {

                for (SocialMediaConnection s : kolInclusion.getSmcList()) {



                    s.setId(IdUtils.simpleUUID());
                    //收录id
                    s.setInclusionId(uuid);
                    s.setCreateBy(currentUser.getUserId().toString());
                    s.setCreateTime(DateUtils.getNowDate());
                    socialMediaConnectionMapper.insertSocialMediaConnection(s);
                }

            }


            if (kolInclusion.getSubmitType().equals("0")) {

                DraftBox draftBox = new DraftBox();
                draftBox.setId(IdUtils.simpleUUID());
                //kol昵称
                draftBox.setName(kolInclusion.getNickname());
                //类型  kol
                draftBox.setType("4");
                draftBox.setProjectId(uuid);
                draftBox.setUserId(currentUser.getUserId().toString());
                draftBox.setCreateBy(currentUser.getUserId().toString());
                draftBox.setCreateTime(DateUtils.getNowDate());
                draftBoxMapper.insertDraftBox(draftBox);
            } else {

                InclusionExamine inclusionExamine = new InclusionExamine();

                inclusionExamine.setId(IdUtils.simpleUUID());
                //未审核
                inclusionExamine.setStatus("0");
                inclusionExamine.setName(kolInclusion.getNickname());
                //类型 kol
                inclusionExamine.setType("4");
                inclusionExamine.setProjectId(uuid);
                inclusionExamine.setUserId(currentUser.getUserId().toString());
                inclusionExamine.setCreateBy(currentUser.getUserId().toString());
                inclusionExamine.setCreateTime(DateUtils.getNowDate());
                inclusionExamineMapper.insertInclusionExamine(inclusionExamine);
            }

        }


        return kolInclusion.getMainId();
    }

    /**
     * 修改KOL收录
     *
     * @param kolInclusion KOL收录
     * @return 结果
     */
    @Override
    public int updateKolInclusion(KolInclusion kolInclusion) {
        kolInclusion.setUpdateTime(DateUtils.getNowDate());
        return kolInclusionMapper.updateKolInclusion(kolInclusion);
    }

    /**
     * 批量删除KOL收录
     *
     * @param ids 需要删除的KOL收录主键
     * @return 结果
     */
    @Override
    public int deleteKolInclusionByIds(String[] ids) {
        return kolInclusionMapper.deleteKolInclusionByIds(ids);
    }

    /**
     * 删除KOL收录信息
     *
     * @param id KOL收录主键
     * @return 结果
     */
    @Override
    public int deleteKolInclusionById(String id) {
        return kolInclusionMapper.deleteKolInclusionById(id);
    }
}
